<template>
  <el-form
    ref="ruleFormRef"
    :model="heartForm"
    :rules="rules"
    class="demo-ruleForm"
    label-position="top"
    size="small"
  >
    <!-- 报文名称 Tel_Name -->
    <el-form-item
      :label="t('pick.telName')"
      prop="telName"
    >
      <el-input
        v-model="heartForm.telName"
        placeholder="请输入报文名称，如 PLCHB"
        maxlength="5"
        show-word-limit
      />
    </el-form-item>

    <!-- 心跳间隔 HB_Time -->
    <el-form-item
      :label="t('pick.hbTime')"
      prop="hbTime"
    >
      <el-input-number
        v-model="heartForm.hbTime"
        :min="100"
        :step="100"
        placeholder="心跳间隔（毫秒）"
      />
    </el-form-item>

    <el-form-item>
      <el-button
        type="primary"
        @click="submitForm(ruleFormRef)"
        :disabled="!pickServerStatus"
        :loading="loading"
      >
        {{ t('pick.send') }}
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">
        {{ t('pick.reset') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { sendMessageByClient } from '@/api/pick'
import { pickStore } from '@/store/pickStore'
import { storeToRefs } from 'pinia'

const store = pickStore()
const { pickServerStatus } = storeToRefs(store)

const { t } = useI18n()
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()

// 表单数据
const heartForm = reactive({
  telName: '', // 报文名称，最多5个字符
  hbTime: 1000 // 心跳间隔，毫秒
})

// 校验规则
const rules = reactive<FormRules>({
  telName: [
    { required: true, message: '请输入报文名称', trigger: 'blur' },
    { min: 1, max: 5, message: '长度不超过 5 个字符', trigger: 'blur' }
  ],
  hbTime: [
    { required: true, message: '请输入心跳间隔（毫秒）', trigger: 'blur' },
    { type: 'number', min: 100, message: '间隔不能小于100毫秒', trigger: 'change' }
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      sendMessageByClient(heartForm).then(res => {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'success',
          duration: 1000
        })
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
